<template>
  <transition appear :name="message.options.animate ? 'slide' : ''" @afterLeave="handleAfterLeave">
    <div class="ant-message-wrap" v-show=message.show>
      <div :class="['ant-message', message.options.type]" @mouseenter="handleMouse('enter')" @mouseleave="handleMouse('leave')">
        <div class="content">{{ message.content }}--{{ id }}</div>
        <i class="close" @click=handleRemove>&times;</i>
      </div>
    </div>
  </transition>
</template>
<script lang="ts">
import {defineComponent, PropType, onUnmounted} from 'vue';
import {MessageItemData} from "./index";

export default defineComponent({
  name: 'MessageItem',
  props: {
    id: {
      type: String,
      require: true
    },
    message: {
      type: Object as PropType<MessageItemData>,
      require: true
    }
  },
  emits: ['close', 'remove'],
  setup(props, { emit }) {
    const { content, options } = props.message!;
    const autoClose = options.duration > 0;
    let timer = 0;
    const handleRemove = () => {
      props.message!.show = false;
      // emit('close', props.id);
    }
    const clearTimer = () => {
      if (timer) {
        clearTimeout(timer);
        timer = 0;
      }
    }
    const createTimer = () => {
      clearTimer();
      timer = setTimeout(() => { handleRemove() }, options.duration);
    }
    onUnmounted(() => {
      // console.log('onUnmounted', props.id);
      clearTimer();
    });
    if (autoClose) {
      createTimer();
    }
    const handleMouse = (type: 'enter' | 'leave') => {
      if (options.pauseOnHover && autoClose) {
        if (type === 'enter') {
          clearTimer();
        } else {
          createTimer();
        }
      }
    }
    const handleAfterLeave = () => {
      emit('remove', props.id);
    }
    return {
      handleAfterLeave,
      handleMouse,
      handleRemove
    }
  }
});

</script>
